import json
import os
from django import forms
from django.core.exceptions import ValidationError
from django.conf import settings
from .models import RbacUser

# 获取项目根目录路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 读取 config.json 文件获取部门信息
config_path = os.path.join(BASE_DIR, 'PM', 'config.json')
try:
    with open(config_path, 'r') as config_file:
        config = json.load(config_file)
        DEPARTMENTS = [(dept, dept) for dept in config.get('DEPARTMENTS', [])]
except FileNotFoundError:
    # 如果配置文件不存在，使用默认部门
    DEPARTMENTS = [
        ('技术部', '技术部'),
        ('销售部', '销售部'), 
        ('市场部', '市场部'),
        ('人事部', '人事部'),
        ('财务部', '财务部'),
    ]


class UserModelForm(forms.ModelForm):
    """用户模型表单"""
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='密码',
        required=False,
        help_text='创建用户时必填，编辑时留空表示不修改密码'
    )
    
    confirm_password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='确认密码',
        required=False
    )
    
    department = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        label='部门',
        required=False,
        help_text='用户所属部门'
    )

    class Meta:
        model = RbacUser
        fields = ['username', 'email', 'first_name', 'last_name']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control'}),
        }
        labels = {
            'username': '用户名',
            'email': '邮箱',
            'first_name': '名',
            'last_name': '姓',
        }

    def clean_email(self):
        """验证邮箱唯一性"""
        email = self.cleaned_data.get('email')
        if email:
            # 如果是编辑现有用户，排除当前用户
            queryset = RbacUser.objects.filter(email=email)
            if self.instance.pk:
                queryset = queryset.exclude(pk=self.instance.pk)
            
            if queryset.exists():
                raise ValidationError('该邮箱已被其他用户使用')
        return email

    def clean_username(self):
        """验证用户名唯一性"""
        username = self.cleaned_data.get('username')
        if username:
            # 如果是编辑现有用户，排除当前用户
            queryset = RbacUser.objects.filter(username=username)
            if self.instance.pk:
                queryset = queryset.exclude(pk=self.instance.pk)
                
            if queryset.exists():
                raise ValidationError('该用户名已被使用')
        return username

    def clean(self):
        """验证密码确认"""
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        # 如果是新用户创建，密码是必填的
        if not self.instance.pk and not password:
            raise ValidationError('创建新用户时密码不能为空')

        # 如果提供了密码，则必须确认密码
        if password and password != confirm_password:
            raise ValidationError('两次输入的密码不一致')

        return cleaned_data


class UserRegistrationForm(UserModelForm):
    """用户注册表单（继承自UserModelForm，但密码是必填的）"""
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='密码',
        required=True,
        min_length=8,
        help_text='密码至少8个字符'
    )
    
    confirm_password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='确认密码',
        required=True
    )

    class Meta(UserModelForm.Meta):
        fields = ['username', 'email', 'first_name', 'last_name']


class LoginForm(forms.Form):
    """登录表单"""
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入邮箱'
        }),
        label='邮箱'
    )
    
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入密码'
        }),
        label='密码'
    )